package cn.lanchengkeji.datafillingsystem.controller;


import cn.lanchengkeji.datafillingsystem.common.Const;
import cn.lanchengkeji.datafillingsystem.common.ResponseBean;
import cn.lanchengkeji.datafillingsystem.common.StatusCode;
import cn.lanchengkeji.datafillingsystem.entity.RqInformantFile;
import cn.lanchengkeji.datafillingsystem.entity.RqTemplate;
import cn.lanchengkeji.datafillingsystem.entity.Users;
import cn.lanchengkeji.datafillingsystem.exception.CommonException;
import cn.lanchengkeji.datafillingsystem.service.IRqInformantFileService;
import cn.lanchengkeji.datafillingsystem.service.IUsersService;
import cn.lanchengkeji.datafillingsystem.utils.Utils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.io.FilenameUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import cn.lanchengkeji.datafillingsystem.controller.BaseController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;

import static com.baomidou.mybatisplus.core.toolkit.IdWorker.getId;

/**
 * <p>
 * 填报文件 前端控制器
 * </p>
 *
 * @author bobobobobo
 * @since 2022-01-20
 */
@RestController
@RequestMapping("/rq-informant-file")
public class RqInformantFileController extends BaseController {


	// 日志
	private static Logger logger = LoggerFactory.getLogger(UploadImgController.class);
	@Resource
	private IUsersService iUsersService;

	@Resource
	private IRqInformantFileService iRqInformantFileService;



	/**
	 *  上传文件
	 * @param imageFile
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/uploadFile",method = RequestMethod.POST)
	@Transactional
	@RequiresAuthentication
	public ResponseBean uploadFile(@RequestParam("file") MultipartFile imageFile, @RequestParam("taskId") Integer taskId,@RequestParam("fileType") Integer fileType, HttpServletRequest request)
			throws Exception{

		// 获取登陆系统用户名，存入日志
		Object obj = SecurityUtils.getSubject().getPrincipal();
		logger.debug((String) obj);
		Users user = iUsersService.getUserByName((String) obj);
		if(imageFile == null ){
			return new ResponseBean(StatusCode.UPLOAD_IMG_NOT_NULL,null);
		}


		QueryWrapper<RqInformantFile> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq(RqInformantFile.TASK_ID , taskId);
		queryWrapper.eq(RqInformantFile.FILE_TYPE , fileType);
		queryWrapper.eq(RqInformantFile.DEL_FLAG , Const.DEL_FLAG_NO);
		List<RqInformantFile> rqInformantFiles = iRqInformantFileService.list(queryWrapper);
		if(Utils.notEmpty(rqInformantFiles) && rqInformantFiles.size() > 0 ){
			for (RqInformantFile rqInformantFile : rqInformantFiles) {
				rqInformantFile.setDelFlag(1);
				iRqInformantFileService.updateById(rqInformantFile);
			}
		}


		String uuid = UUID.randomUUID().toString();


		// 获取文件名称
		String fileName = imageFile.getOriginalFilename();
		// 获取文件大小
		long fileSize = imageFile.getSize();

//		// 获取文件类型
//		String fileType = fileName.split("\\.")[fileName.split("\\.").length - 1];
//		if(!fileType.equals("sht")){
//			throw new CommonException(StatusCode.FILE_NOT_TEXT_FOUND.getCode(), StatusCode.FILE_NOT_TEXT_FOUND.getMsg());
//		}


		//拼接后台文件名称
		String pathName = "";

		pathName =  File.separator + uuid + "." + FilenameUtils.getExtension(imageFile.getOriginalFilename());
		// 获取当前操作系统
		String os = System.getProperty("os.name");

		String urlString;

		if (os.toLowerCase().startsWith("win")) {
			urlString = Const.UPLOAD_FILE_PATH_WIN + "/" + user.getId() + taskId;
		} else {
			urlString = Const.UPLOAD_FILE_PATH_LIN + "/" + user.getId() + taskId;
		}

		//拼接文件路劲
//        String filePathName = realPath + File.separator + pathName;
		String filePathName = urlString + "/"+ fileName;
		logger.info("文件上传路径："+filePathName);

		//判断文件保存是否存在
		File file = new File(filePathName);
		if (file.getParentFile() != null || !file.getParentFile().isDirectory()) {
			//创建文件
			file.getParentFile().mkdirs();
		}

		InputStream inputStream = imageFile.getInputStream();
		FileOutputStream fileOutputStream = new FileOutputStream(file);

		try {

			byte[] buffer = new byte[1024*1024];
			int byteRead = 0;
			while((byteRead=inputStream.read(buffer))!=-1) {
				fileOutputStream.write(buffer,0,byteRead);
			}

		} catch (IOException e) {
			filePathName = null;
			return new ResponseBean(StatusCode.OK_FAIL, e.getMessage());
		} finally {
			try {

				fileOutputStream.flush();
				fileOutputStream.close();
			} catch (IOException e) {
				logger.debug("loadProperties IOException:" + e.getMessage());
			}

			try {
				inputStream.close();
			} catch (IOException e) {
				logger.debug("loadProperties IOException:" + e.getMessage());
			}
		}

		Map<String, Object> map = new HashMap<String, Object>();
		//原图地址
		map.put("pathUrl", (urlString + pathName).replace("\\\\","\\"));

		// 返回地址

		String addressUrl = "";


		addressUrl = "/" + fileName + "."
				+ FilenameUtils.getExtension(imageFile.getOriginalFilename());
		map.put("pathUrl2",addressUrl);

		FileInputStream fileInputStream = new FileInputStream(filePathName);


		fileInputStream.close();


		map.put("fileSize",fileSize);

		QueryWrapper<RqInformantFile> rqInformantFileQueryWrapper = new QueryWrapper<>();
		rqInformantFileQueryWrapper.eq(RqInformantFile.DEL_FLAG ,Const.DEL_FLAG_NO);
		List<RqInformantFile> list = iRqInformantFileService.list(rqInformantFileQueryWrapper);
		for (RqInformantFile rqInformantFile : list) {
			if(Utils.notEmpty(rqInformantFile.getFileName())){
				if(rqInformantFile.getFileName().equals(fileName)){
					throw new CommonException(StatusCode.FILE_NAME_NOT_SAME.getCode(), StatusCode.FILE_NAME_NOT_SAME.getMsg());
				}
			}
		}


		RqInformantFile rqInformantFile = new RqInformantFile();
		rqInformantFile.setTaskId(taskId);
		rqInformantFile.setFilePath(filePathName);
		rqInformantFile.setFileName(fileName);
		rqInformantFile.setFileType(fileType);

		return new ResponseBean(StatusCode.OK, rqInformantFile);
	}



	/**
	 *  上传文件
	 * @param rqInformantFile
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/uploadPath",method = RequestMethod.POST)
	@Transactional
	@RequiresAuthentication
	public ResponseBean path(@RequestBody RqInformantFile rqInformantFile)throws Exception {
		RqInformantFile rqInformantFiles = new RqInformantFile();
		rqInformantFiles.setTaskId(rqInformantFile.getTaskId());
		rqInformantFiles.setFileType(rqInformantFile.getFileType());
		rqInformantFiles.setFilePath(rqInformantFile.getFilePath());
		boolean ret = iRqInformantFileService.save(rqInformantFiles);
		return new ResponseBean(StatusCode.OK, ret);
	}

	/**
	 *  详情
	 * @param rqInformantFile
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getOne",method = RequestMethod.POST)
	@Transactional
	@RequiresAuthentication
	public ResponseBean getOne(@RequestBody RqInformantFile rqInformantFile)throws Exception {
		if(Utils.isEmpty(rqInformantFile.getTaskId())){
			throw new CommonException(StatusCode.OK_FAIL.getCode(), StatusCode.OK_FAIL.getMsg());
		}
		QueryWrapper<RqInformantFile> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq(RqInformantFile.DEL_FLAG , Const.DEL_FLAG_NO);
		queryWrapper.eq(RqInformantFile.TASK_ID , rqInformantFile.getTaskId());
		List<RqInformantFile> list = iRqInformantFileService.list(queryWrapper);
		return new ResponseBean(StatusCode.OK, list);
	}


	/**
	 *  上传文件
	 * @param rqInformantFile
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/saveByFile",method = RequestMethod.POST)
	@Transactional
	@RequiresAuthentication
	public ResponseBean saveByFile(@RequestBody List<RqInformantFile> rqInformantFile)throws Exception {
		boolean ret = false ;
		for (RqInformantFile informantFile : rqInformantFile) {
			 ret = iRqInformantFileService.save(informantFile);
		}
		return new ResponseBean(StatusCode.OK, ret);
	}

	/**
	 * 文件审核
	 * @param rqInformantFile
	 * @return
	 */
	@RequestMapping(value = "/check", method = RequestMethod.POST)
	@Transactional
	@RequiresAuthentication
	public ResponseBean check(@RequestBody RqInformantFile rqInformantFile)throws Exception {
		// 获取登陆系统用户名，存入日志
		Object obj = SecurityUtils.getSubject().getPrincipal();
		logger.debug((String) obj);
		Users user = iUsersService.getUserByName((String) obj);

		QueryWrapper<RqInformantFile> rqInformantFileQueryWrapper = new QueryWrapper<>();
		rqInformantFileQueryWrapper.eq(RqInformantFile.ID ,rqInformantFile.getId());
		RqInformantFile one = iRqInformantFileService.getOne(rqInformantFileQueryWrapper);
		one.setCheckType(rqInformantFile.getCheckType());
		boolean ret = iRqInformantFileService.updateById(one);

		return new ResponseBean(StatusCode.OK, ret);
	}

}
